package cn.jsxz.common.utils.WeiXinUtil;


import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Lucas
 * @date 2018/1/26
 * @package cn.dckeji.jiakao.common.utils
 * @Description 微信工具类
 */
public class WxUtils {

    private static final Logger LOGGER = Logger.getLogger(WxUtils.class);


    /**
     * xml转map
     *
     * @param xmlString
     * @return
     */
    public static Map xmlToMap(String xmlString) {
        Document document = null;
        Map map = new HashMap();
        try {
            document = DocumentHelper.parseText(xmlString);
            Element rootElement = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = rootElement.elements();

            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 解析微信返回的xml
     *
     * @param request
     */
    public static Map parseXml(HttpServletRequest request) {

        InputStream inputStream = null;
        Map map = new HashMap();
        try {
            inputStream = request.getInputStream();
            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = rootElement.elements();

            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 查询ip
     *
     * @return
     */
    public static String getIp() {
        InetAddress ia = null;
        try {
            ia = InetAddress.getLocalHost();
            String localip = ia.getHostAddress();
            return localip;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 请求xml组装
     *
     * @param parameters
     * @return
     */
    public static String getRequestXml(SortedMap<String, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
                sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key + ">");
            } else {
                sb.append("<" + key + ">" + value + "</" + key + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 解析XML 获得名称为para的参数值
     *
     * @param xml
     * @param para
     * @return
     */
    public static String getXmlPara(String xml, String para) {
        int start = xml.indexOf("<" + para + ">");
        int end = xml.indexOf("</" + para + ">");

        if (start < 0 && end < 0) {
            return null;
        }
        return xml.substring(start + ("<" + para + ">").length(), end).replace("<![CDATA[", "").replace("]]>", "");
    }
}
